<template>
  <div class="single-param-analysis">
    <!-- 顶部筛选区 -->
    <div class="top-filter-panel">
      <el-card shadow="never" class="filter-card">
        <el-form :model="filterForm" class="filter-form">
          <div class="filter-row">
            <!-- 参数选择 -->
            <el-form-item label="参数选择" class="filter-item">
              <el-cascader v-model="filterForm.selectedParam" :options="paramOptions" :props="cascaderProps"
                placeholder="请选择参数" style="width: 100%" clearable />
            </el-form-item>

            <!-- 数据来源 -->
            <el-form-item label="数据来源" class="filter-item">
              <el-select v-model="filterForm.facilityIds" multiple placeholder="请选择设施" style="width: 100%" clearable>
                <el-option v-for="facility in facilities" :key="facility.facilityId" :label="facility.facilityName"
                  :value="facility.facilityId" />
              </el-select>
            </el-form-item>

            <!-- 刷新频率 -->
            <el-form-item label="刷新频率" class="filter-item">
              <el-select v-model="refreshInterval" placeholder="实时刷新" style="width: 100%">
                <el-option label="实时" value="realtime" />
                <el-option label="5秒" value="5s" />
                <el-option label="30秒" value="30s" />
                <el-option label="不刷新" value="none" />
              </el-select>
            </el-form-item>

            <el-form-item class="filter-item filter-actions">
              <el-button type="primary" @click="handleSearch" :loading="loading">
                查询
              </el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </div>

          <div class="filter-row">
            <!-- 时间筛选 -->
            <el-form-item label="时间范围" class="filter-item time-range-item">
              <div class="time-range-wrapper">
                <el-radio-group v-model="quickTimeType" @change="onQuickTimeChange" size="small">
                  <el-radio-button label="last1hour">近1小时</el-radio-button>
                  <el-radio-button label="last6hours">近6小时</el-radio-button>
                  <el-radio-button label="today">今日</el-radio-button>
                  <el-radio-button label="yesterday">昨日</el-radio-button>
                </el-radio-group>
                <el-date-picker v-model="timeRange" type="datetimerange" range-separator="至" start-placeholder="开始时间"
                  end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="x" :default-time="defaultTime"
                  @change="onTimeRangeChange" style="width: 100%; margin-top: 8px;" />
              </div>
            </el-form-item>

            <el-form-item class="filter-item">
              <el-checkbox v-model="showAbnormalMark">显示异常标记</el-checkbox>
            </el-form-item>
          </div>
        </el-form>
      </el-card>
    </div>

    <div class="main-content">
      <!-- 中间可视化区 -->
      <div class="visualization-panel">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3 class="chart-title">{{ chartTitle }}</h3>
              <div class="chart-actions">
                <el-button size="small" @click="exportChart">导出图表</el-button>
                <el-button size="small" @click="toggleFullscreen">
                  {{ isFullscreen ? '退出全屏' : '全屏' }}
                </el-button>
              </div>
            </div>
          </template>

          <div ref="chartRef" class="chart-container" :class="{ 'fullscreen-chart': isFullscreen }"></div>
        </el-card>
      </div>

      <!-- 右侧辅助区 -->
      <div class="side-panel">
        <el-card shadow="never" class="info-card">
          <template #header>
            <div class="card-header">
              <h4>参数信息</h4>
            </div>
          </template>

          <div v-if="currentParam" class="param-info">
            <div class="info-item">
              <label>参数名称：</label>
              <span>{{ currentParam.paramName }}</span>
            </div>
            <div class="info-item">
              <label>参数类型：</label>
              <span>{{ currentParam.paramType }}</span>
            </div>
            <div class="info-item">
              <label>参数单位：</label>
              <span>{{ currentParam.paramUnit }}</span>
            </div>
            <div class="info-item">
              <label>正常范围：</label>
              <span>{{ currentParam.standardMin }} - {{ currentParam.standardMax }} {{ currentParam.paramUnit }}</span>
            </div>
            <div class="info-item" v-if="historicalAvg">
              <label>历史同期均值：</label>
              <span>{{ historicalAvg }} {{ currentParam.paramUnit }}</span>
            </div>
          </div>

          <!-- 统计指标 -->
          <div class="stat-summary" v-if="statData">
            <el-divider>统计摘要</el-divider>
            <div class="stat-item">
              <div class="stat-value">{{ statData.currentValue || '-' }}</div>
              <div class="stat-label">当前值</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ statData.avgValue || '-' }}</div>
              <div class="stat-label">平均值</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ statData.maxValue || '-' }}</div>
              <div class="stat-label">最大值</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ statData.minValue || '-' }}</div>
              <div class="stat-label">最小值</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ statData.abnormalCount || 0 }}</div>
              <div class="stat-label">异常次数</div>
            </div>
          </div>
        </el-card>

        <!-- 实时预警 -->
        <el-card shadow="never" class="warning-panel" v-if="realtimeWarnings.length > 0">
          <template #header>
            <div class="card-header">
              <h4>实时预警</h4>
            </div>
          </template>
          <div class="warning-list">
            <div v-for="warning in realtimeWarnings" :key="warning.id" class="warning-item"
              @click="handleWarningClick(warning)">
              <el-alert :title="`${warning.facilityName} ${warning.paramName}异常`"
                :description="`当前值: ${warning.value}${warning.unit}, 时间: ${formatDate(warning.time)}`" type="warning"
                :closable="false" show-icon />
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 底部数据详情区 -->
    <div class="data-panel">
      <el-card shadow="never" class="table-card">
        <template #header>
          <div class="table-header">
            <h3 class="table-title">数据详情</h3>
            <div class="table-actions">
              <el-button size="small" @click="exportData">导出Excel</el-button>
              <el-button size="small" @click="toggleAutoRefresh" :type="autoRefresh ? 'primary' : ''">
                {{ autoRefresh ? '停止刷新' : '自动刷新' }}
              </el-button>
            </div>
          </div>
        </template>

        <el-table :data="tableData" stripe style="width: 100%" v-loading="loading" @row-click="onTableRowClick"
          :row-class-name="getRowClassName" :key="`table-${showAbnormalMark}`" class="data-table">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="monitorTime" label="监测时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.monitorTime, 'yyyy-MM-dd HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column prop="facilityName" label="设施名称" width="120" />
          <el-table-column prop="monitorValue" label="参数值" width="120">
            <template #default="{ row }">
              <span :class="getValueClass(row)">
                {{ row.monitorValue }} {{ row.paramUnit }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="dataStatus" label="数据状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.dataStatus === 1 ? 'danger' : 'success'" size="small">
                {{ row.dataStatus === 1 ? '异常' : '正常' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="deviceId" label="采集设备" width="120" />
          <el-table-column prop="installPosition" label="安装位置" min-width="150" />
          <el-table-column prop="dataSource" label="数据来源" width="120" />
          <el-table-column label="操作" width="150" fixed="right" align="center">
            <template #default="{ row }">
              <el-button v-if="row.dataStatus === 1" link type="primary" size="small" @click.stop="handleAbnormalDetail(row)">
                异常详情
              </el-button>
              <el-button link type="primary" size="small" @click.stop="handleViewHistory(row)">
                历史记录
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 异常详情对话框 -->
    <el-dialog v-model="abnormalDetailVisible" title="异常详情" width="600px">
      <div v-if="selectedAbnormalData" class="abnormal-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="异常时间">
            {{ formatDate(selectedAbnormalData.monitorTime, 'yyyy-MM-dd HH:mm:ss') }}
          </el-descriptions-item>
          <el-descriptions-item label="设施名称">
            {{ selectedAbnormalData.facilityName }}
          </el-descriptions-item>
          <el-descriptions-item label="参数名称">
            {{ selectedAbnormalData.paramName }}
          </el-descriptions-item>
          <el-descriptions-item label="异常值">
            {{ selectedAbnormalData.monitorValue }} {{ selectedAbnormalData.paramUnit }}
          </el-descriptions-item>
          <el-descriptions-item label="正常范围">
            {{ selectedAbnormalData.standardMin }} - {{ selectedAbnormalData.standardMax }} {{
              selectedAbnormalData.paramUnit }}
          </el-descriptions-item>
          <el-descriptions-item label="偏差率">
            <span :class="getDeviationRateClass(selectedAbnormalData.deviationRate)">
              {{ selectedAbnormalData.deviationRate ? (selectedAbnormalData.deviationRate * 100).toFixed(2) + '%' : '-'
              }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="采集设备" :span="2">
            {{ selectedAbnormalData.deviceId }} - {{ selectedAbnormalData.dataSource }}
          </el-descriptions-item>
          <el-descriptions-item label="安装位置" :span="2">
            {{ selectedAbnormalData.installPosition }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="abnormal-actions" style="margin-top: 20px;">
          <el-button type="primary" @click="handleReportAbnormal(selectedAbnormalData)">
            异常上报
          </el-button>
          <el-button @click="handleViewSimilarAbnormal(selectedAbnormalData)">
            查看相似异常
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 异常上报对话框 -->
    <el-dialog v-model="abnormalReportVisible" title="异常上报" width="500px">
      <el-form :model="abnormalForm" label-width="100px">
        <el-form-item label="异常时间">
          <span>{{ formatDate(abnormalForm.monitorTime, 'yyyy-MM-dd HH:mm:ss') }}</span>
        </el-form-item>
        <el-form-item label="设施名称">
          <span>{{ abnormalForm.facilityName }}</span>
        </el-form-item>
        <el-form-item label="参数名称">
          <span>{{ abnormalForm.paramName }}</span>
        </el-form-item>
        <el-form-item label="异常值">
          <span>{{ abnormalForm.monitorValue }} {{ abnormalForm.paramUnit }}</span>
        </el-form-item>
        <el-form-item label="正常范围">
          <span>{{ abnormalForm.standardMin }} - {{ abnormalForm.standardMax }} {{ abnormalForm.paramUnit }}</span>
        </el-form-item>
        <el-form-item label="异常描述">
          <el-input v-model="abnormalForm.description" type="textarea" :rows="3" placeholder="请描述异常情况、可能原因及建议措施" />
        </el-form-item>
        <el-form-item label="紧急程度">
          <el-radio-group v-model="abnormalForm.urgency">
            <el-radio label="low">低</el-radio>
            <el-radio label="medium">中</el-radio>
            <el-radio label="high">高</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="abnormalReportVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReportAbnormal">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import {
  getFacilities,
  getParams,
  singleParamAnalysis
} from '@/api/prod_operate/prod_run/measurement_analysis'
import { formatDate, getQuickTimeRange } from '@/utils/date'

// 响应式数据
const loading = ref(false)
const autoRefresh = ref(false)
const refreshInterval = ref('none')
const showAbnormalMark = ref(true)
const isFullscreen = ref(false)

// 筛选表单
const filterForm = reactive({
  selectedParam: [],
  facilityIds: []
})

const quickTimeType = ref('last6hours')
const timeRange = ref([])
const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 1, 1, 23, 59, 59)
]

// 基础数据
const facilities = ref([])
const paramOptions = ref([])
const cascaderProps = {
  value: 'paramId',
  label: 'paramName',
  children: 'children'
}

// 图表相关
const chartRef = ref()
const chartTitle = ref('单参数趋势分析')
let chartInstance = null

// 当前参数信息
const currentParam = ref(null)
const historicalAvg = ref(null)

// 数据
const tableData = ref([])
const statData = ref(null)
const realtimeWarnings = ref([])

// 对话框控制
const abnormalDetailVisible = ref(false)
const abnormalReportVisible = ref(false)
const selectedAbnormalData = ref(null)
const abnormalForm = reactive({
  monitorTime: '',
  facilityName: '',
  paramName: '',
  monitorValue: '',
  paramUnit: '',
  standardMin: '',
  standardMax: '',
  description: '',
  urgency: 'medium'
})

// 定时器
let refreshTimer = null

// 初始化
onMounted(() => {
  initData()
  initChart()
  initTimeRange()
})

// 初始化数据
const initData = async () => {
  try {
    await loadFacilities()
    await loadParams()
  } catch (error) {
    ElMessage.error('数据加载失败')
  }
}

// 加载设施数据
const loadFacilities = async () => {
  const res = await getFacilities()
  if (res.success) {
    facilities.value = res.data
  }
}

// 加载参数数据
const loadParams = async () => {
  const res = await getParams()
  if (res.success) {
    // 按参数类型分组
    const paramGroups = {}
    res.data.forEach(param => {
      if (!paramGroups[param.paramType]) {
        paramGroups[param.paramType] = []
      }
      paramGroups[param.paramType].push({
        paramId: param.paramId,
        paramName: param.paramName,
        paramUnit: param.paramUnit,
        standardMin: param.standardMin,
        standardMax: param.standardMax
      })
    })

    paramOptions.value = Object.keys(paramGroups).map(type => ({
      paramId: type,
      paramName: type,
      children: paramGroups[type]
    }))

    // 默认选择第一个参数
    if (paramOptions.value.length > 0 && paramOptions.value[0].children.length > 0) {
      filterForm.selectedParam = [paramOptions.value[0].paramId, paramOptions.value[0].children[0].paramId]
      currentParam.value = paramOptions.value[0].children[0]
    }
  }
}

// 初始化时间范围
const initTimeRange = () => {
  const range = getQuickTimeRange(quickTimeType.value)
  timeRange.value = [range.startTime, range.endTime]
}

// 初始化图表
const initChart = () => {
  nextTick(() => {
    if (chartRef.value) {
      chartInstance = echarts.init(chartRef.value)
      window.addEventListener('resize', handleResize)
    }
  })
}

// 处理窗口大小变化
const handleResize = () => {
  chartInstance?.resize()
}

// 时间筛选变化
const onQuickTimeChange = () => {
  initTimeRange()
}

const onTimeRangeChange = () => {
  quickTimeType.value = ''
}

// 查询数据
const handleSearch = async () => {
  if (!filterForm.selectedParam || filterForm.selectedParam.length !== 2) {
    ElMessage.warning('请选择参数')
    return
  }

  if (!timeRange.value || timeRange.value.length !== 2) {
    ElMessage.warning('请选择时间范围')
    return
  }

  loading.value = true
  try {
    const paramId = filterForm.selectedParam[1]
    const params = {
      paramId: paramId,
      facilityIds: filterForm.facilityIds,
      startTime: timeRange.value[0],
      endTime: timeRange.value[1]
    }

    const res = await singleParamAnalysis(params)
    if (res.success) {
      tableData.value = res.data
      updateChart(res.data)
      updateStatData(res.data)
      updateRealtimeWarnings(res.abnormalData)

      // 更新图表标题
      const paramName = currentParam.value?.paramName || '参数'
      chartTitle.value = `${paramName}趋势图 (${formatDate(timeRange.value[0], 'MM-dd HH:mm')} - ${formatDate(timeRange.value[1], 'MM-dd HH:mm')})`
    }
  } catch (error) {
    ElMessage.error('查询失败')
  } finally {
    loading.value = false
  }
}

// 更新图表
const updateChart = (data) => {
  if (!chartInstance || !data.length) return

  // 按设施分组数据
  const facilityData = {}
  const timeSet = new Set()

  data.forEach(item => {
    const facilityName = item.facilityName
    const timeKey = formatDate(item.monitorTime, 'MM-dd HH:mm:ss')

    if (!facilityData[facilityName]) {
      facilityData[facilityName] = {
        name: facilityName,
        type: 'line',
        data: [],
        symbol: item.dataStatus === 1 ? 'circle' : 'none',
        symbolSize: item.dataStatus === 1 ? 6 : 0,
        itemStyle: {
          color: item.dataStatus === 1 ? '#f56c6c' : '#409eff'
        }
      }
    }

    timeSet.add(timeKey)
  })

  // 构建时间轴
  const timeArray = Array.from(timeSet).sort()

  // 填充数据
  timeArray.forEach(time => {
    Object.keys(facilityData).forEach(facility => {
      const item = data.find(d =>
        formatDate(d.monitorTime, 'MM-dd HH:mm:ss') === time &&
        d.facilityName === facility
      )
      facilityData[facility].data.push(item ? item.monitorValue : null)
    })
  })

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let result = `${params[0].axisValue}<br/>`
        params.forEach(param => {
          const item = data.find(d =>
            formatDate(d.monitorTime, 'MM-dd HH:mm:ss') === params[0].axisValue &&
            d.facilityName === param.seriesName
          )
          const status = item?.dataStatus === 1 ? '（异常）' : ''
          result += `${param.seriesName}: ${param.value}${status}<br/>`
        })
        return result
      }
    },
    legend: {
      data: Object.keys(facilityData),
      type: 'scroll',
      bottom: 50,
      itemGap: 20
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '25%',
      containLabel: true
    },
    toolbox: {
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        },
        restore: {},
        saveAsImage: {}
      }
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        type: 'slider',
        start: 0,
        end: 100,
        bottom: 10,
        height: 30
      }
    ],
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: timeArray
    },
    yAxis: {
      type: 'value',
      name: currentParam.value?.paramUnit || ''
    },
    series: Object.values(facilityData)
  }

  // 添加正常范围线
  if (currentParam.value && showAbnormalMark.value) {
    option.series.push(
      {
        name: '上限',
        type: 'line',
        data: timeArray.map(() => currentParam.value.standardMax),
        lineStyle: {
          type: 'dashed',
          color: '#f56c6c'
        },
        symbol: 'none',
        itemStyle: {
          color: '#f56c6c'
        }
      },
      {
        name: '下限',
        type: 'line',
        data: timeArray.map(() => currentParam.value.standardMin),
        lineStyle: {
          type: 'dashed',
          color: '#f56c6c'
        },
        symbol: 'none',
        itemStyle: {
          color: '#f56c6c'
        }
      }
    )
  }

  chartInstance.setOption(option, true)
}

// 更新统计数据
const updateStatData = (data) => {
  if (!data.length) {
    statData.value = null
    return
  }

  const values = data.map(d => d.monitorValue).filter(v => v != null)
  const abnormalCount = data.filter(d => d.dataStatus === 1).length

  statData.value = {
    currentValue: data[data.length - 1]?.monitorValue,
    avgValue: values.length ? (values.reduce((a, b) => a + b, 0) / values.length).toFixed(2) : null,
    maxValue: values.length ? Math.max(...values).toFixed(2) : null,
    minValue: values.length ? Math.min(...values).toFixed(2) : null,
    abnormalCount: abnormalCount
  }
}

// 更新实时预警
const updateRealtimeWarnings = (abnormalData) => {
  realtimeWarnings.value = abnormalData.slice(0, 5).map(item => ({
    id: item.dataId,
    facilityName: item.facilityName,
    paramName: item.paramName,
    value: item.monitorValue,
    unit: item.paramUnit,
    time: item.monitorTime
  }))
}

// 重置筛选条件
const handleReset = () => {
  filterForm.selectedParam = []
  filterForm.facilityIds = []
  quickTimeType.value = 'last6hours'
  initTimeRange()
  refreshInterval.value = 'none'
  showAbnormalMark.value = true

  // 重新选择默认参数
  if (paramOptions.value.length > 0 && paramOptions.value[0].children.length > 0) {
    filterForm.selectedParam = [paramOptions.value[0].paramId, paramOptions.value[0].children[0].paramId]
  }
}

// 表格行点击事件
const onTableRowClick = (row) => {
  // 在图表中高亮对应数据点
  if (chartInstance) {
    const pointIndex = tableData.value.findIndex(item =>
      item.dataId === row.dataId
    )
    if (pointIndex !== -1) {
      chartInstance.dispatchAction({
        type: 'showTip',
        seriesIndex: 0,
        dataIndex: pointIndex
      })
    }
  }
}

// 获取表格行样式
const getRowClassName = ({ row }) => {
  // 如果未启用异常标记显示，则不应用异常样式
  if (!showAbnormalMark.value) return ''
  return row.dataStatus === 1 ? 'abnormal-row' : ''
}

// 获取数值样式
const getValueClass = (row) => {
  // 如果未启用异常标记显示，则不应用异常样式
  if (!showAbnormalMark.value) return 'normal-value'
  if (row.dataStatus === 1) return 'abnormal-value'
  return 'normal-value'
}

// 获取偏差率样式
const getDeviationRateClass = (deviationRate) => {
  if (!deviationRate) return ''
  const absRate = Math.abs(deviationRate)
  if (absRate > 0.1) return 'deviation-high'
  if (absRate > 0.05) return 'deviation-medium'
  return 'deviation-low'
}

// 异常详情
const handleAbnormalDetail = (row) => {
  selectedAbnormalData.value = row
  abnormalDetailVisible.value = true
}

// 异常上报
const handleReportAbnormal = (row) => {
  Object.assign(abnormalForm, {
    monitorTime: row.monitorTime,
    facilityName: row.facilityName,
    paramName: row.paramName,
    monitorValue: row.monitorValue,
    paramUnit: row.paramUnit,
    standardMin: row.standardMin,
    standardMax: row.standardMax,
    description: '',
    urgency: 'medium'
  })
  abnormalReportVisible.value = true
  abnormalDetailVisible.value = false
}

const confirmReportAbnormal = () => {
  ElMessage.success('异常上报成功')
  abnormalReportVisible.value = false
}

// 查看历史记录
const handleViewHistory = (row) => {
  // 设置筛选条件为当前设施和参数
  filterForm.selectedParam = [row.paramType, row.paramId]
  filterForm.facilityIds = [row.facilityId]

  // 设置时间为最近24小时
  quickTimeType.value = 'last24hours'
  initTimeRange()

  ElMessage.info('已切换到该设施的历史数据视图')
}

// 查看相似异常
const handleViewSimilarAbnormal = (row) => {
  ElMessage.info('查看相似异常功能开发中')
}

// 预警点击事件
const handleWarningClick = (warning) => {
  // 定位到对应的数据行
  const row = tableData.value.find(item => item.dataId === warning.id)
  if (row) {
    onTableRowClick(row)
    handleAbnormalDetail(row)
  }
}

// 切换全屏
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
  nextTick(() => {
    chartInstance?.resize()
  })
}

// 切换自动刷新
const toggleAutoRefresh = () => {
  autoRefresh.value = !autoRefresh.value

  if (autoRefresh.value) {
    startAutoRefresh()
  } else {
    stopAutoRefresh()
  }
}

// 开始自动刷新
const startAutoRefresh = () => {
  const intervalMap = {
    'realtime': 5000,
    '5s': 5000,
    '30s': 30000
  }

  const interval = intervalMap[refreshInterval.value] || 5000

  refreshTimer = setInterval(() => {
    if (filterForm.selectedParam.length === 2) {
      handleSearch()
    }
  }, interval)
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

// 导出功能
const exportChart = () => {
  if (chartInstance) {
    const chartDataURL = chartInstance.getDataURL({
      type: 'png',
      pixelRatio: 2,
      backgroundColor: '#fff'
    })
    const link = document.createElement('a')
    link.href = chartDataURL
    link.download = `${currentParam.value?.paramName || '参数'}趋势图.png`
    link.click()
  }
}

const exportData = () => {
  ElMessage.info('导出功能开发中')
}

// 监听参数选择变化
watch(() => filterForm.selectedParam, (newVal) => {
  if (newVal && newVal.length === 2) {
    // 找到选中的参数信息
    const typeGroup = paramOptions.value.find(group => group.paramId === newVal[0])
    if (typeGroup) {
      const param = typeGroup.children.find(p => p.paramId === newVal[1])
      if (param) {
        currentParam.value = param
      }
    }
  }
})

// 监听刷新间隔变化
watch(refreshInterval, (newVal) => {
  if (autoRefresh.value) {
    stopAutoRefresh()
    if (newVal !== 'none') {
      startAutoRefresh()
    } else {
      autoRefresh.value = false
    }
  }
})

// 监听自动刷新状态
watch(autoRefresh, (newVal) => {
  if (!newVal) {
    stopAutoRefresh()
  }
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chartInstance?.dispose()
  stopAutoRefresh()
})
</script>

<style scoped>
.single-param-analysis {
  padding: 16px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 筛选区样式 */
.top-filter-panel {
  margin-bottom: 16px;
}

.filter-card {
  border-radius: 8px;
}

.filter-form {
  padding: 4px 0;
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: flex-start;
  margin-bottom: 16px;
}

.filter-row:last-child {
  margin-bottom: 0;
}

.filter-item {
  flex: 1;
  min-width: 200px;
  margin-bottom: 0;
}

.filter-item.time-range-item {
  flex: 2;
  min-width: 400px;
}

.filter-actions {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  flex: 0 0 auto;
}

.time-range-wrapper {
  width: 100%;
}

/* 主内容区样式 */
.main-content {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  min-height: 500px;
}

.visualization-panel {
  flex: 1;
  min-width: 0;
}

.chart-card {
  border-radius: 8px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.chart-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-actions {
  display: flex;
  gap: 8px;
}

.chart-container {
  height: 450px;
  width: 100%;
  min-height: 400px;
}

.fullscreen-chart {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw !important;
  height: 100vh !important;
  z-index: 9999;
  background: white;
  padding: 20px;
}

/* 侧边栏样式 */
.side-panel {
  width: 320px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-card,
.warning-panel {
  border-radius: 8px;
}

.card-header {
  padding: 0;
}

.card-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.param-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item label {
  font-weight: 500;
  color: #606266;
  font-size: 13px;
  flex-shrink: 0;
  margin-right: 12px;
}

.info-item span {
  color: #303133;
  text-align: right;
  word-break: break-all;
}

.stat-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 8px;
}

.stat-item {
  flex: 1;
  min-width: calc(20% - 10px);
  text-align: center;
  padding: 16px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  transition: all 0.3s;
}

.stat-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 6px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.warning-panel {
  max-height: 400px;
  overflow-y: auto;
}

.warning-list {
  max-height: 350px;
  overflow-y: auto;
}

.warning-item {
  margin-bottom: 12px;
  cursor: pointer;
  transition: transform 0.2s;
}

.warning-item:hover {
  transform: translateX(4px);
}

.warning-item:last-child {
  margin-bottom: 0;
}

/* 数据表格区样式 */
.data-panel {
  margin-bottom: 16px;
}

.table-card {
  border-radius: 8px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.table-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.data-table {
  width: 100%;
}

/* 对话框样式 */
.abnormal-detail {
  max-height: 400px;
  overflow-y: auto;
}

.abnormal-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-top: 20px;
}

/* 表格行样式 */
:deep(.abnormal-row) {
  background-color: #fef0f0 !important;
}

:deep(.abnormal-row:hover) {
  background-color: #fde2e2 !important;
}

.abnormal-value {
  color: #f56c6c;
  font-weight: bold;
}

.normal-value {
  color: #67c23a;
}

.deviation-high {
  color: #f56c6c;
  font-weight: bold;
}

.deviation-medium {
  color: #e6a23c;
}

.deviation-low {
  color: #67c23a;
}

/* 响应式布局 */
@media (max-width: 1400px) {
  .side-panel {
    width: 280px;
  }
  
  .chart-container {
    height: 400px;
  }
}

@media (max-width: 1200px) {
  .main-content {
    flex-direction: column;
  }
  
  .side-panel {
    width: 100%;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
  }
  
  .warning-panel {
    grid-column: 1 / -1;
  }
}

@media (max-width: 768px) {
  .single-param-analysis {
    padding: 12px;
  }
  
  .filter-row {
    flex-direction: column;
  }
  
  .filter-item {
    width: 100%;
    min-width: 100%;
  }
  
  .filter-item.time-range-item {
    min-width: 100%;
  }
  
  .side-panel {
    grid-template-columns: 1fr;
  }
  
  .chart-container {
    height: 350px;
  }
  
  .stat-item {
    min-width: calc(50% - 6px);
  }
}
</style>